package main

import (
	"fmt"
	"net/http"
	"os"
	"strings"

	"com.JudgeServer/Tools"
	"github.com/gin-gonic/gin"
)

var dev int = 0

func test1(i int) int {
	return i + 1
}
func SplictString(res string) []string {

	if strings.Contains(res, "|") {
		l := strings.Split(res, "|")
		return l
	} else {
		return []string{res}
	}
}
func main() {

	if dev == 0 {
		r := gin.Default()
		r.POST("/Judge", func(c *gin.Context) {
			Code := c.DefaultPostForm("Code", "")
			input := c.DefaultPostForm("input", "")
			result := c.DefaultPostForm("result", "")
			Type := c.DefaultPostForm("type", "")
			fmt.Print(c.GetHeader("Content-Type"))
			fmt.Print(c.Get("Code"))
			print(Code)
			print(SplictString(result)[0])
			c.JSON(http.StatusOK, Tools.StartCompile(Code, SplictString(input), SplictString(result), Type))
		})
		r.Use(Cors())
		r.Run(":9998")
	} else {
		gotest()
	}
}

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")
		//放行所有OPTIONS方法
		if method == "OPTIONS" {

			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}
func gotest() {
	result := make([]string, 3)
	result[0] = "2"
	result[1] = "3"
	result[2] = "4"
	input := make([]string, 3)
	input[0] = "1"
	input[1] = "2"
	input[2] = "6"
	goTest := "package main\n" +
		"import (\"os\"" +
		"\"strconv\"\n)" +
		"func test1(i int) int {\n" +
		"return i + 1\n" +
		"}\n" +
		"func main() {\n" +
		"arg,_:=strconv.Atoi(os.Args[2])\n" +
		"print(test1(arg))\n" +
		"}\n"
	Tools.StartCompile(goTest, input, result, "go")
}

//测试程序
func test() {
	// userCode := "import sys\n" +
	// 	"def test(i):\n" +
	// 	"	return i+1\n" +
	// 	"args=sys.argv\n" +
	// 	"print(test(int(args[2])))"
	by, _ := os.ReadFile("./CodingFIle/test.java")
	userCode := string(by)
	result := make([]string, 3)
	result[0] = "2"
	result[1] = "3"
	result[2] = "4"
	input := make([]string, 3)
	input[0] = "1"
	input[1] = "2"
	input[2] = "6"
	res := Tools.StartCompile(userCode, input, result, "Java")
	print(res.JundgeResType)
}
